
def template(_template,_n=5,**kwargs):
	import os
	import re
	from string import Template

	replace=r">>> d01aR <<<"
	_template = re.sub(r"[{][$][}]",replace,_template)
	t = Template(_template)
	for i in range(_n):
		s = t.safe_substitute(**kwargs)
		t = Template(s)

	files = re.findall(r"[$]{(tab)?file:([^},]+)(,[^}]+)?}",s)
	if files:
		for kind,file,default in files:
			if os.path.exists(file):
				f = open(file,"r").read()
				f = re.sub(r"[{][$][}]",replace,f)
				if kind=="tab":
					f=f.replace("\n","\n\t")
				s = s.replace("${%sfile:%s%s}"%(kind,file,default),f)
			else:
				s = s.replace("${%sfile:%s%s}"%(kind,file,default),default[1:])

	defaults = re.findall(r"[$]{([^},]+)[,]([^}]*)}",s)
	for k,v in defaults:
		if k not in kwargs:
			kwargs[k]=v
	s = re.sub(r"[$]{([^},]+)[,]([^}]*)}","${\\1}",s)

	t = Template(s)
	for i in range(_n):
		s = t.safe_substitute(**kwargs)
		t = Template(s)
	s = re.sub(replace,"$",s)
	return s

if __name__=="__main__":
	print template(r">>>$xxx<<<",x=321,z=777)

